var URL_START = "http://host.bisswanger.com/dhbw/calendar.php";
var USER = "80085";

/*
 * Caches all calendar entries offline for faster access and traffic reduction.
 * 
 * Provides functions to easily find events or categories by id.
 */
var storage = {
    categories: null,
    events: null,
    
    
    /**
     * Gets the category with the given id.
     * 
     * @param {int} categoryId
     * @returns {Category} Category or null.
     */
    findCategory: function(categoryId) {
        categoryId = "" + categoryId;
        for (var i = 0; i < this.categories.length; i++) {
            if (this.categories[i].id === categoryId) {
                return this.categories[i];
            }
        }
        
        return null; // not contained
    },
    
    /**
     * Returns the id of the category with the given name or null.
     * 
     * @param {type} categoryName
     * @returns {storage_L81@arr;categories@pro;id}
     */
    findCategoryId: function(categoryName) {
        for (var i = 0; i < this.categories.length; i++) {
            if (this.categories[i].name === categoryName) {
                return this.categories[i].id;
            }
        }
        
        return null; // not contained
    },
    
    /**
     * Gets the event with the given id.
     * 
     * @param {String} eventId
     * @returns {undefined} Event or null.
     */
    findEvent: function(eventId) {
        eventId = "" + eventId; // be sure it is a string
        for (var i = 0; i < this.events.length; i++) {
            if (this.events[i].id === eventId) {
                return this.events[i];
            }
        }
        
        return null; // not contained
    }
};

/**
 * Helper function which formats the given date into a human readable string.
 * 
 * @param {Date} date
 * @returns {String}
 */
function formatDate(date) {
    var monthNames = ["Jan", "Feb", "Mar",
        "Apr", "May", "June", "July", "Aug", "Sept",
        "Oct", "Nov", "Dec"];
    var str = "" + date.getUTCMinutes();
    // we do not want to display the time
    if (str.length === 1) {
        str = "0" + str;
    }
    return date.getUTCDate() + ". " + monthNames[date.getMonth()] + " " + date.getUTCFullYear() + " " + date.getUTCHours() + ":" + str;
}

/**
 * Alerts a error coming from an XMLHttpRequest. 
 * Prints the error id and the text.
 * 
 * @param {XMLHttpRequest} request request where the error occured
 * @param {String} action action which was done with the request
 */
function alertError(request, action) {
    if (request.responseText && JSON.parse(request.responseText).error) {
        alert("Error in action \"" + action + "\": "
                + JSON.parse(request.responseText).error.id + " "
                + JSON.parse(request.responseText).error.text
                + " in readystate: " + request.readyState);
    }
}
